import { Circle, Color, Svg } from "@svgdotjs/svg.js";
import { MassPoint } from "./lib/phy";
import { PhySystem } from "./system";
import { MultMassPointVideo } from "./video";

export interface Interval {
    finish: () => void,
}

export const updateInterval = (
    update: (dt: number) => void,
    dt: number,
): Interval => {
    const intervalId = setInterval(() => update(dt), dt * 1000);
    const finish = () => { clearInterval(intervalId); }
    return { finish };
}

export const massPointRender = (
    system: PhySystem<MassPoint[]>,
    rendingDt: number,
    svg: Svg,
) => {
    const pointMap: Map<MassPoint, Circle> = new Map();

    system.state.forEach(point => {
        pointMap.set(point, svg.circle(5).attr({ fill: Color.random() }));
    });

    const update = (dt: number) => {
        system.update(dt);
        pointMap.forEach((circle, point) =>
            circle.move(point.p.x, point.p.y));
    };

    return updateInterval(update, rendingDt);
}

export const videoRender = (
    video: MultMassPointVideo,
    rendingDt: number,
    svg: Svg,
) => {
    const circleList = video.pList.map(_ =>
        svg.circle(5).attr({ fill: Color.random() }));


    let rendingTime = 0;
    let interval: Interval;
    let update_i = (dt: number) => {
        rendingTime += dt;
        const recordIndex = Math.floor(rendingTime / video.recordDt);

        if (recordIndex >= video.pList[0].length) {
            interval.finish();
            return;
        }
        circleList.forEach((circle, index) => {
            const p = video.pList[index][recordIndex];
            circle.move(p.x, p.y);
        });
    };
    interval = updateInterval(update_i, rendingDt)
    return interval;
}
